package com.onluy.frameworkcloud.tools.utils;



import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA
 *
 * @Author v-yo@qq.com
 * @Description JWT 工具类
 * @Date 2018-04-07
 * @Time 22:48
 */
public class JWTUtil {
//    // 过期时间 24 小时
//    private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;
//    // 密钥
//    private static final String SECRET = "SHIRO+JWT";

    /**
     * 生成 token
     *
     * @param userInfo 用户信息
     * @return 加密的token
     */
    public static String createToken(JSONObject userInfo, String secret, long expireTime) throws UnsupportedEncodingException {
        Date date = new Date(System.currentTimeMillis() + expireTime);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder=JWT.create();

        for(String key:userInfo.keySet()) {
            builder.withClaim(key,  userInfo.getString(key)  );
        }
        builder.withExpiresAt(date);//到期时间

        String tokenValue=builder.sign(algorithm);

        tokenValue = Base64Utils.encode(tokenValue.getBytes("UTF-8"));
        return  tokenValue;
    }

    /**
     * 校验 token 是否正确
     *
     * @param token    密钥
     * @param key 关键字
     * @param value 值
     * @return 是否正确
     */
    public static boolean contains(String token,String secret, String key,String value) {
        try {

            token = new String(Base64Utils.decode(token.getBytes("UTF-8")));
            Algorithm algorithm = Algorithm.HMAC256(secret);
            //在token中附带了username信息
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim(key, value)
                    .build();
            //验证 token
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息，无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getTokenKeyValue(String token,String key)   {
        try {
            token = new String(Base64Utils.decode(token.getBytes("UTF-8")));
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(key).asString();
        } catch (Exception exception) {
            return null;
        }
    }
}